/**
 * 
 */
package com.scpii.universal.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.stereotype.Service;

import com.googlecode.ehcache.annotations.TriggersRemove;
import com.googlecode.ehcache.annotations.When;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.UserInfoDto;
import com.scpii.universal.hibernate.dao.AttributeDao;
import com.scpii.universal.hibernate.dao.AttributeValueDao;
import com.scpii.universal.hibernate.dao.ClientUserDao;
import com.scpii.universal.hibernate.dao.ContentDao;
import com.scpii.universal.hibernate.entity.AttributeTab;
import com.scpii.universal.hibernate.entity.AttributeValueTab;
import com.scpii.universal.hibernate.entity.ClientUserTab;
import com.scpii.universal.hibernate.entity.ContentTab;
import com.scpii.universal.service.CatelogService;
import com.scpii.universal.service.ContentService;
import com.scpii.universal.util.ExcelHelper;

/**
 * genericWeb
 * @author weny
 * 2012-7-8下午09:40:56
 */
@Service
public class ContentServiceImpl extends BaseServiceImpl<ContentTab, Integer>
		implements ContentService {
	@Resource
	private ContentDao contentDao;
	@Resource
	private AttributeDao attributeDao;
	@Resource
	private AttributeValueDao attributeValueDao;
	@Resource
	private CatelogService CatelogService;
	@Resource
	private ClientUserDao clientUserDao;
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Resource
	public void setBaseDao(ContentDao contentDao) {
		super.setBaseDao(contentDao);
	}

	@Override
	public void topContentSortOrder(int intConentId, int intCateId) {
		int maxSortOrder = contentDao.getMaxSortOrder(intCateId)+1;
		updateOrder(intConentId, maxSortOrder);
	}
	
	/**
	 * 更新内容置顶顺序
	 * @author Taylor
	 * 2012-11-25 下午04:35:44
	 * @param intConentId
	 * @param sortOrder
	 * void
	 */
	private void updateOrder(int intConentId,int sortOrder) {
		StringBuffer hql = new StringBuffer("update ContentTab c set ");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		hql.append(" c.intSortOrder=:intSortOrder");
		argsMap.put("intSortOrder", sortOrder);
		hql.append(" where c.intContentId=:intContentId");
		argsMap.put("intContentId", intConentId);
		contentDao.hqlOperation(hql.toString(), argsMap);
	}

	@Override
	public void cancelContentTop(int intContentId) {
		updateOrder(intContentId, 0);
	}

	@Override
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,when=When.AFTER_METHOD_INVOCATION,removeAll=true)
	public void saveContentsFromExcel(int intCateId, String[] heads, List<String> contents, UserInfoDto userInfo, int[] mappingIndex) {
		int contLen = contents.size();
		int[] attrIds = getAllAttrIds(intCateId, heads);
		String date = sdf.format(new Date());
		AttributeValueTab value = null;
		List<ClientUserTab> users = clientUserDao.getAllUserByAppId(userInfo.getAppId());
//		List<ContentTab> allConts = contentDao.getByUserCateIds(0, intCateId);
		for (int i = 1; i < contLen; i++) {
			String row = contents.get(i);
			String[] columns = row.split(ExcelHelper.SEPARATOR);
			ContentTab content = getByUserCateIds(mappingIndex, intCateId,columns,userInfo,null,users);
			attributeValueDao.deleteByContId(content.getIntContentId());
			for (int j = 1; j < columns.length; j++) {
				if( StringUtils.isBlank(columns[j]) || columnsFilter(mappingIndex,j))
					continue;
				value = new AttributeValueTab();
				value.setDatMudifyDate(date);
				value.setIntAttriId(attrIds[j-1]);
				value.setIntContentId(content.getIntContentId());
				value.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
				value.setVarAttriValue(columns[j]);
				attributeValueDao.save(value);
			}
			if (i % 500 == 0) {
				contentDao.flushAndClear();
			}
		}
	}
	
	private boolean columnsFilter(int[] mappingIndex, int index) {
		for (int i : mappingIndex) {
			if (i == index)
				return true;
		}
		return false;
	}
	
	private int[] getAllAttrIds(int intCateId, String[] heads) {
		List<AttributeTab> attrs = CatelogService.getAllAttributesByCateId(intCateId);
		int headLen = heads.length;
		int[] result = new int[headLen-1];
		String date = sdf.format(new Date());
		AttributeTab attr = null;
		for (int i = 1; i < headLen; i++) {
			int id = getAttrIdByName(attrs, heads[i].trim());
			if (id == 0) {
				attr = new AttributeTab();
				attr.setIntCateId(intCateId);
				attr.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
				attr.setVarAttriName(heads[i].trim());
				attr.setDatUpdateDatetime(date);
				attr.setIntInputType(GenericConstants.ATTRIBUTE_INPUT_TYPE_INPUT);
				attr.setIntType(0);
				result[i-1] = attributeDao.save(attr);
			} else {
				result[i-1] = id;
			}
		}
		return result;
	}
	
	private int getAttrIdByName(List<AttributeTab> attrs, String name) {
		int id = 0;
		for (AttributeTab attr : attrs) {
			if (name.equals(attr.getVarAttriName())) {
				id = attr.getIntAttriId();
				break;
			}
		}
		return id;
	}
	
	private int checkUserExist(String loginName,int appId, String password,List<ClientUserTab> users) {
		ClientUserTab user = null;
//		user = clientUserDao.getUserByLoginName(loginName, appId);
		if (users != null && users.size() > 0 && !StringUtils.isBlank(loginName)) {
			for (ClientUserTab clientUserTab : users) {
				if (!StringUtils.isBlank(clientUserTab.getVarUserPhonenum())
						&& clientUserTab.getVarUserPhonenum().equals(loginName)) {
					user = clientUserTab;
					break;
				}
			}
		}
		if (user == null) {
			user = new ClientUserTab();
			user.setDatUpdateDatetime(sdf.format(new Date()));
			user.setVarUserPhonenum(loginName);
			user.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			user.setIntAppId(appId);
			user.setVarUserLoginPassword(password);
			clientUserDao.save(user);
			users.add(user);
		}
		return user.getIntUserId();
	}
	
	private ContentTab getByUserCateIds(int[] mappingIndex, int cateId,
			String[] columns, UserInfoDto userInfo, List<ContentTab> contents,
			List<ClientUserTab> users) {
		int userId = 0;
		String contentName = mappingIndex[2]==-1 ? ( mappingIndex[0] > 0? columns[mappingIndex[0]].trim():columns[1].trim()) : columns[mappingIndex[2]].trim();
		if( mappingIndex[0] > 0) {
			userId = checkUserExist(columns[mappingIndex[0]].trim(),
					userInfo.getAppId(), mappingIndex[1] == -1 ? null : columns[mappingIndex[1]], users);
		}
		ContentTab content = null;
//		if (contents == null || contents.size() <= 0) {
		String date = sdf.format(new Date());
		content = new ContentTab();
		content.setVarContentName(contentName);
		content.setVarContentImgUrl(mappingIndex[3]>0?columns[mappingIndex[3]].trim():null);
		content.setVarContentDescript(mappingIndex[4]>0?columns[mappingIndex[4]].trim():null);
		content.setIntEnterpId(userInfo.getIntEnterpId());
		content.setIntCateId(cateId);
		content.setIntAppId(userInfo.getAppId());
		content.setDatAddDatetime(date);
		content.setIntViewCount(0);
		content.setIntAction(0);
		content.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST); 
		content.setDatUpdateDatetime(date);
		content.setIntResourceId(0l);
		content.setIntSortOrder(0);
		content.setIntPrivilegeUser((long)userId);
		contentDao.save(content);
//		} else {
//			for (ContentTab contentTab : contents) {
//				if(contentTab.getIntPrivilegeUser().intValue() == userId) {
//					content = contentTab;
//					break;
//				}
//			}
//		}
		return content;
	}
}
